package top.surgeqi.security.jwt.config.extend;

import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * <p><em>Created by qipp on 2020/7/01 10:41</em></p>
 * 扩展DaoAuthenticationProvider
 * <blockquote><pre>
 *     扩展登录时
 *     密码方式认证在验证密码时改为在认证器中完成
 *     非密码认证方式认证过程也在认证器中完成即可
 * </pre></blockquote>
 *
 * @author <a href="https://gitee.com/qipengpai">qipp</a>
 * @since 1.0.1
 */
public class ExtendAuthDaoAuthenticationProvider extends DaoAuthenticationProvider {

    public ExtendAuthDaoAuthenticationProvider(UserDetailsService userDetailsService) {
        super();
        // 这个地方一定要对userDetailsService赋值，不然userDetailsService是null (这个坑有点深)
        setUserDetailsService(userDetailsService);
    }

    /**
     * 不再校验密码
     * 具体校验在认证器中以及完毕
     *
     * @param userDetails    用户详情对象
     * @param authentication 用户认证详情
     * @throws AuthenticationException 认证异常
     */
    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        if (authentication.getCredentials() == null) {
            this.logger.debug("Authentication failed: no credentials provided");
            throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
        }
    }
}
